<script setup lang="ts">
import { ref, onMounted } from "vue";
import { marked } from "marked";

const regions = [
    { id: "china", name: "国内" },
    { id: "us", name: "美国" },
    { id: "hk", name: "香港" },
    { id: "global", name: "全球" },
];

interface RegionState {
    loading: boolean;
    error: string | null;
    analysisResult: any;
}

const regionStates = ref<Record<string, RegionState>>(
    Object.fromEntries(
        regions.map((region) => [
            region.id,
            { loading: false, error: null, analysisResult: null },
        ])
    )
);

const parseAnalysisContent = (content: string) => {
    const sections: Record<string, string> = {};
    const parts = content.split(/(?=###)/);

    parts.forEach((part) => {
        const trimmedPart = part.trim();
        if (trimmedPart) {
            const titleMatch = trimmedPart.match(/^### (.+)/);
            if (titleMatch) {
                const title = titleMatch[1];
                const content = trimmedPart.replace(/^### .+\n/, "").trim();
                sections[title] = marked(content);
            }
        }
    });

    return sections;
};

const fetchNewsAnalysis = async (region: string) => {
    const state = regionStates.value[region];
    state.loading = true;
    state.error = null;

    try {
        const response = await fetch(
            `http://localhost:20010/analyze/${region}`
        );
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        state.analysisResult = data;
    } catch (e) {
        state.error = e instanceof Error ? e.message : "获取新闻分析失败";
    } finally {
        state.loading = false;
    }
};

const refreshAnalysis = (region: string) => {
    fetchNewsAnalysis(region);
};

onMounted(() => {
    regions.forEach((region) => {
        fetchNewsAnalysis(region.id);
    });
});
</script>

<template>
    <div class="news-analyzer">
        <h1 class="main-title">财经新闻分析</h1>
        <div class="grid-container">
            <div v-for="region in regions" :key="region.id" class="region-card">
                <div class="region-header">
                    <h2>{{ region.name }}市场分析</h2>
                    <button
                        @click="refreshAnalysis(region.id)"
                        :disabled="regionStates[region.id].loading"
                        class="refresh-btn"
                    >
                        {{
                            regionStates[region.id].loading
                                ? "加载中..."
                                : "刷新"
                        }}
                    </button>
                </div>

                <div v-if="regionStates[region.id].error" class="error-message">
                    {{ regionStates[region.id].error }}
                </div>

                <div v-if="regionStates[region.id].loading" class="loading">
                    <div class="spinner"></div>
                    <p>正在分析新闻...</p>
                </div>

                <div
                    v-if="
                        !regionStates[region.id].loading &&
                        !regionStates[region.id].error &&
                        regionStates[region.id].analysisResult
                    "
                    class="content"
                >
                    <template
                        v-if="regionStates[region.id].analysisResult?.analysis"
                    >
                        <div class="analysis-sections">
                            <div
                                v-for="(section, index) in parseAnalysisContent(regionStates[region.id].analysisResult!.analysis)"
                                :key="index"
                                class="section"
                            >
                                <h3>{{ index }}</h3>
                                <div
                                    class="section-content markdown-body"
                                    v-html="section"
                                ></div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.news-analyzer {
    max-width: 1600px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.main-title {
    text-align: center;
    margin-bottom: 30px;
    color: #2c3e50;
    font-size: 1.8em;
}

.region-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    position: relative;
}

.region-header h2 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.3em;
}

.refresh-btn {
    padding: 8px 16px;
    border: none;
    border-radius: 6px;
    background-color: #4a90e2;
    color: white;
    cursor: pointer;
    font-size: 0.9em;
    transition: background-color 0.3s ease;
}

.refresh-btn:hover {
    background-color: #357abd;
}

.refresh-btn:disabled {
    background-color: #a0a0a0;
    cursor: not-allowed;
}

.section-content {
    font-size: 0.85em;
    line-height: 1.6;
}

.grid-container {
    display: grid;
    grid-template-columns: 1fr;
    gap: 30px;
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.region-card {
    background: white;
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    width: 100%;
}

.region-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 15px rgba(0, 0, 0, 0.15);
}

.analysis-sections {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 25px;
    margin-top: 20px;
}

.section {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 20px;
    transition: background-color 0.3s ease;
}

.section:hover {
    background: #f0f2f5;
}

.section h3 {
    color: #2c3e50;
    margin-bottom: 15px;
    font-size: 1.3em;
    font-weight: 600;
    text-align: left;
}

.section-content {
    font-size: 0.95em;
    line-height: 1.8;
    color: #4a5568;
    text-align: left;
}

.markdown-body ul {
    list-style-type: disc;
    padding-left: 25px;
    margin: 15px 0;
}

.markdown-body ul li {
    margin-bottom: 10px;
    line-height: 1.6;
}

.error-message {
    color: #e53e3e;
    margin: 10px 0;
    padding: 10px;
    background-color: #fff5f5;
    border-radius: 8px;
    text-align: center;
}

.loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 10px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
</style>